package com.android.jingweiapp.fragment.information;

import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.android.jingweiapp.R;
import com.android.jingweiapp.XMLPhase.ImportantNewsXMLPhase;
import com.android.jingweiapp.activity.DetailTextActivity;
import com.android.jingweiapp.activity.SearchActivity;
import com.android.jingweiapp.adapter.CommonAdapter;
import com.android.jingweiapp.bean.NewsBean;
import com.android.jingweiapp.util.Contacts;
import com.android.jingweiapp.util.HttpUtil;
import com.android.jingweiapp.widget.MyToast;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;

import butterknife.Bind;
import butterknife.ButterKnife;

/**
 * 重要新闻
 */
public class ImportantNewsFragment extends Fragment {

    @Bind(R.id.et_search)
    EditText etSearch;
    @Bind(R.id.btn_search)
    TextView btnSearch;
    @Bind(R.id.list_news)
    ListView listImportant;

    private ArrayList<NewsBean> newsBeans;
    private int offset = 1;
    private CommonAdapter adapter;
    private RelativeLayout layoutFooter;
    private MyAsyncTask myAsynctask;
    private boolean needLoading = true;
    private boolean isLoading = false;


    public ImportantNewsFragment() {
        // Required empty public constructor
    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View view = inflater.inflate(R.layout.fragment_important_news, container, false);
        ButterKnife.bind(this, view);
        init();
        return view;
    }


    public void init() {
        btnSearch.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(getActivity(), SearchActivity.class);
                String str = etSearch.getText().toString();
                intent.putExtra(Contacts.KEY.SEARCH_KEYWORD, TextUtils.isEmpty(str) ? " " : str);
                startActivity(intent);
            }
        });

        newsBeans = new ArrayList<>();
        adapter = new CommonAdapter(newsBeans, getActivity());
        listImportant.setAdapter(adapter);
        layoutFooter = (RelativeLayout) LayoutInflater.from(getActivity()).inflate(
                R.layout.listview_footer, null);
        listImportant.addFooterView(layoutFooter);

        listImportant.setOnItemClickListener(new MyOnItemClickListener());
        listImportant.setOnScrollListener(new MyOnScrollListener());

        myAsynctask = new MyAsyncTask();
        myAsynctask.execute();

    }


    private void dealData(String result) {
        layoutFooter.setVisibility(View.GONE);
        if (TextUtils.isEmpty(result)) {
            MyToast.getInstance().show("出错了，请重试");
            return;
        }
        if (result.equals("nodata")) {
            needLoading = false;
            if (adapter.getCount() > 0) {
                MyToast.getInstance().show("出错了，请重试");
            } else {
                MyToast.getInstance().show("无更多数据");
            }
            return;
        }
        try {
            JSONObject jsonObject = new JSONObject(result);
            JSONArray array = jsonObject.getJSONArray("data");
            for (int i = 0; i < array.length(); i++) {
                newsBeans.add(new NewsBean(array.getJSONObject(i)));
            }
            if (array.length() < 20) {
                needLoading = false;
            }
            adapter.notifyDataSetChanged();
            isLoading = false;
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        ButterKnife.unbind(this);
    }

    class MyOnItemClickListener implements AdapterView.OnItemClickListener {

        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            startActivity(new Intent(getActivity(), DetailTextActivity.class)
                    .putExtra(Contacts.KEY.KEY_OBJECT, newsBeans.get(position))
                    .putExtra(Contacts.KEY.KEY_TYPE, Contacts.TYPE.TEXT_NEWS));
        }
    }

    class MyOnScrollListener implements AbsListView.OnScrollListener {
        private int lastItemIndex;


        @Override
        public void onScrollStateChanged(AbsListView view, int scrollState) {
            if (needLoading && !isLoading && lastItemIndex >= adapter.getCount() - 3) {
                layoutFooter.setVisibility(View.VISIBLE);
                offset++;
                myAsynctask = new MyAsyncTask();
                myAsynctask.execute();
            }
        }

        @Override
        public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount,
                             int totalItemCount) {
            lastItemIndex = firstVisibleItem + visibleItemCount - 2;
        }
    }

    class MyAsyncTask extends AsyncTask<String, Integer, String> {
        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            isLoading = true;
        }


        @Override
        protected String doInBackground(String[] params) {
            return HttpUtil.postWithContent(Contacts.BASE_URL,
                    ImportantNewsXMLPhase.createParam(getActivity(), String.valueOf(offset)),
                    new ImportantNewsXMLPhase());
        }

        @Override
        protected void onPostExecute(String str) {
            super.onPostExecute(str);
            dealData(str);
        }
    }

}